package net.dgg.dggcloud.core.util;

import net.dgg.dggcloud.core.exception.BaseException;
import net.dgg.dggcloud.core.exception.DggcloudCoreException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 验证工具类，验证不通过抛出指定异常
 *
 * @author 徐哲
 * @create 2017-11-08 17:13
 */
public class ValidateUtil {

	/**
	 * 构造异常
	 * @param exceptionClass
	 * @param msg
	 * @param <T>
	 * @return
	 */
	private static <T extends RuntimeException> T constructException(Class<T> exceptionClass,String msg){
		T exception= null;

		Constructor constructor= null;
		try {
			constructor = exceptionClass.getConstructor(String.class);
		} catch (NoSuchMethodException e) {
			throw new DggcloudCoreException("缺少String为参数的构造函数",DggcloudCoreException.DEFAULT_CODE,e);
		}
		try {
			exception = (T) constructor.newInstance(msg);
		} catch (InstantiationException e) {
			throw new DggcloudCoreException(e.getMessage(),DggcloudCoreException.DEFAULT_CODE,e);
		} catch (IllegalAccessException e) {
			throw new DggcloudCoreException(e.getMessage(),DggcloudCoreException.DEFAULT_CODE,e);
		} catch (InvocationTargetException e) {
			throw new DggcloudCoreException(e.getMessage(),DggcloudCoreException.DEFAULT_CODE,e);
		}


		return exception;
	}

	/**
	 * 非空校验
	 * @param data 被校验的对象
	 * @param exceptionClass 抛出的异常类型
	 * @param msg 异常时的报错信息，如果为null，则为默认信息
	 * @param <T>异常类型必须是RuntimeException的派生类
	 */
	public static <T extends RuntimeException> void notNull(Object data,Class<T> exceptionClass,String msg){
		if(data==null){
			throw constructException(exceptionClass,msg==null?"内容不可为null":msg);
		}
	}

	//String 不为空
	//String 长度不超过指定位数
	//String 长度不短于指定位数
	//String 符合指定正则表达式
	//int 应该大于某个值
	//int 应该小于某个值
	//long 应该大于某个值
	//long 应该小于某个值
}